
//获取地址栏传来的参数
var flag = 0;

function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);//search,查询？后面的参数，并匹配正则
    if (r != null) return unescape(r[2]);
    return null;
}


//获取表名
var Reporttablename = GetQueryString("tablename");
//获取与表名对应的所有报告


//加载版本号
function AddVersion() {
    $.ajax({
        url: "/test/web/api/report/FindAllVersion",
        data: {tablename: Reporttablename},
        type: "Post",
        //async:falase,

        success: function (data) {
            if (data.code != null) {
                var code = data.code;
                var message = data.message;
                if (code == "400") {
                    alert(message);
                    window.parent.location.href = "/login.html";
                }
                else if (code == "401") {
                    alert(message);
                    window.location.href = "/error/error.html";
                }
                return;
            }

            var items = "";
            var item = "";
            $.each(data, function (i, result) {
                item = "<option value='" + result + "'>" + result + "</option>";
                items += item;
            });
            items += "<option selected='selected' value=''>所有版本</option>";
            $('#version_select').html(items);
            search();
        }

    });
}
//按日期查找
function search() {
    highchartsFlag=0;
    flag = 1;
    document.getElementById("box_center").style.display = "block";
    document.getElementById("highchart").style.display = "block";
    document.getElementById("box_bottom2").style.display = "none";
    document.getElementById("case_table").style.display = "none";
    document.getElementById("box_bottom").style.display = "block";

    var version = document.getElementById("version_select").value;
    var allsuccesssum = 0;
    var allcasenum = 0;
    var start = document.getElementById("start_time").value;
    var end = document.getElementById("end_time").value;
    if (start == "" || end == "") return;
    var tablename = Reporttablename;
    var casetablename = "";
    switch (tablename) {
        case 'test_service_api_report' :
            casetablename = "test_service_api_case";
            break;
        case 'online_service_api_report' :
            casetablename = "online_service_api_case";
            break;
        case 'qa_service_api_report' :
            casetablename = "qa_service_api_case";
            break;
        case 'gray_service_api_report' :
            casetablename = "gray_service_api_case";
            break;
    }
    $.ajaxSettings.async = false;
    var countnum = 0;
    $("#show_table").bootstrapTable('destroy');
    $('#show_table').bootstrapTable({
        url: "/test/web/api/report/FindAllReportByTime",
        method: 'post',
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        cache: false,
        queryParams: queryParams,
        striped: true,
        pagination: true,
        sortable: true,
        // sortOrder: "asc",//升序
        sortOrder: "desc",//降序
        sortName: 'reporttime',
        sidePagination: 'client',
        pageSize: 10,
        pageNumber: 1,
        pageList: [10, 20, 50, 100, 200, 500],
        search: true,
        strictSearch: false,
        showColumns: true,
        showRefresh: false,
        showExport: false,
        uniqueId: "rid",
        showToggle: false,
        cardView: false,
        // clickToSelect: true,
        showFooter: true,

        columns:
            [
                // {field: "checked", checkbox: true},
                {field: "rid", title: "编号", align: "center", valign: "middle", sortable: "true"},
                {field: "type", title: "类型", align: "center", valign: "middle", sortable: "true"},
                {field: "version", title: "版本", align: "center", valign: "middle", sortable: "true"},
                {
                    field: "jobname",
                    title: "名称",
                    align: "center",
                    valign: "middle",
                    sortable: "true",
                    formatter: Addbutton
                },
                {
                    field: "casenum",
                    title: "总数",
                    align: "center",
                    valign: "middle",
                    sortable: "true",
                    footerFormatter: Conutnum
                },
                {field: "successnum", title: "成功", align: "center", valign: "middle", sortable: "true"},
                {field: "failnum", title: "失败", align: "center", valign: "middle", sortable: "true"},
                {field: "reporttime", title: "时间", align: "center", valign: "middle", sortable: "true"},
            ],

    });

    function Conutnum(value) {
        var count = 0;
        var successconut = 0;
        console.log(value);
        for (var i = 0; i < value.length; i++) {
            count += parseFloat(JSON.parse(JSON.stringify(value[i])).casenum);
            successconut += parseFloat(JSON.parse(JSON.stringify(value[i])).successnum);
        }
        allcasenum = count;
        allsuccesssum = successconut;
        return "Total:" + count + ",Success:" + successconut;
    }


    function Addbutton(value, row, index) {
        //   alert(row.id+"索引"+index);
        return [
            '<button class="btn btn-default" style="width: 100%;background-color: #9fcdff"  onclick="FindCaseByRid(\'' + row.rid + '\',\'' + casetablename + '\',\''+row.casenum+'\',\''+row.successnum+'\')">' + value + '</button>'
        ].join("")
    }

    function queryParams(params) {
        return {
            tablename: tablename,
            start: start,
            end: end,
            version: version
        }
    }

    //alert("totla"+allcasenum+"success"+allsuccesssum);
    Highcharts.chart('highchart', {
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie'
        },
        title: {
            text: 'CASE运行结果占比'
        },
        tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                    style: {
                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                    }
                }
            }
        },
        series: [{
            name: 'Brands',
            colorByPoint: true,
            data: [{
                name: '成功 :' + allsuccesssum + "条  占比",
                y: allsuccesssum / allcasenum,
                sliced: true,
                selected: true
            }, {
                name: '失败 :' + (allcasenum - allsuccesssum) + "条  占比",
                y: (allcasenum - allsuccesssum) / allcasenum,
            },]
        }]
    });
}

/**
 * highchartsFlag 用于解决接口测试中 详情页返回至CASE列表时 饼图不加载的BUG
 * @type {number}
 */
var highchartsFlag=0;


//查询每条报告对应的CASE
var temprid, temptablename;//记录用于返回
function FindCaseByRid(rid, tablename,r_casenum,r_successnum) {
    flag = 2;
    temprid = rid;
    temptablename = tablename;
    document.getElementById("box_center").style.display = "none";
    document.getElementById("highchart").style.display = "block";
    document.getElementById("box_bottom2").style.display = "none";
    document.getElementById("box_bottom").style.display = "none";
    document.getElementById("case_table").style.display = "block";

    $.ajax({
        url: "/test/web/api/case/FindByRid", //处理页面的路径
        data: {rid: rid, tablename: tablename},//要提交的数据是一个JSON
        type: "POST", //提交方式
        success: function (data) { //回调函数 ,成功时返回的数据存在形参data里
            var items = '';
            items += data;
            $('#case_table').html(items);
        }
    });
    if(highchartsFlag==0){
    chart = Highcharts.chart('highchart', {
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie'
        },
        title: {
            text: 'CASE运行结果占比'
        },
        tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                    style: {
                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                    }
                }
            }
        },
        series: [{
            name: 'Brands',
            colorByPoint: true,
            data: [{
                name: '成功 :' + r_successnum + "条  占比",
                y: r_successnum / r_casenum,
                sliced: true,
                selected: true
            }, {
                name: '失败 :' + (r_casenum - r_successnum) + "条  占比",
                y: (r_casenum - r_successnum) / r_casenum,
            },]
        }]
    });}


}

//问题跟进
function updatetrack(cid, tablename) {
    var trcakcontent = document.getElementById("trcakcontent").value;
    $.ajax({
        url: "/test/web/api/detail/UpdateTrackBycid", //处理页面的路径
        data: {cid: cid, tablename: tablename, track: trcakcontent},//要提交的数据是一个JSON
        type: "POST", //提交方式
        async: false,
        success: function (data) { //回调函数 ,成功时返回的数据存在形参data里
            alert(data);
        }
    });
}

function SendEmail(cid, tablename) {
    var emailaddr = document.getElementById("emailaddr").value;
    $.ajax({
        url: "/test/web/api/detail/SendEmail", //处理页面的路径
        data: {emailaddr: emailaddr, cid: cid, tablename: tablename},//要提交的数据是一个JSON
        type: "POST", //提交方式
        //TEXT字符串 JSON返回JSON XML返回XML
        success: function (data) { //回调函数 ,成功时返回的数据存在形参data里
            if (data.code != null) {
                var code = data.code;
                var message = data.message;
                if (code == "400") {
                    alert(message);
                    window.parent.location.href = "/login.html";
                }
                else if (code == "401") {
                    alert(message);
                   // window.location.href = "/error/error.html";
                }
                return ;
            }
            alert(data);
        }
    });
}

//查询每条CASE对应的日志
function FindDetailByCid(cid, tablename) {
    flag = 3;
    document.getElementById("highchart").style.display = "none";
    document.getElementById("box_bottom2").style.display = "block";
    document.getElementById("box_bottom").style.display = "none";
    document.getElementById("case_table").style.display = "none";
    // $("#show_table").bootstrapTable('destroy');
    $.ajax({
        url: "/test/web/api/detail/FindByCid", //处理页面的路径
        data: {cid: cid, tablename: tablename},//要提交的数据是一个JSON
        type: "POST", //提交方式
        success: function (data) { //回调函数 ,成功时返回的数据存在形参data里
            var item;
            var items = '';
            items += "<tr><th width='200'>" + "测试接口" + "</th><th width='800'>" + "详细信息" + "</th></tr>";
            $.each(data, function (i, result) {
                item = "<tr><td>" + result['api'] + "</td><td><textarea readonly='readonly' style='width: 100% ;height: 400px;'>" + result['detail'] + "</textarea></td></tr>";
                items += item;
                var temptrack = result['track'];
                if (temptrack == null) temptrack = " ";
                items += "<tr><td>问题跟进</td><td><textarea id='trcakcontent' style='width: 100%;height: 200px'>" + temptrack + "</textarea></td><td ><button class='ui_input_btn01'onclick='updatetrack(\"" + cid + "\",\"" + tablename + "\")'>提交</button></td></tr>";
                items += "<tr><td>通过邮件发送日志</td><td><input style='width: 100%; height:25px;' id='emailaddr' type='text' class='form-control' value='请输入邮箱地址，多个邮箱用逗号分隔' onfocus=\"this.value = '';\"onblur=\"if (this.value == '') {this.value = '请输入邮箱地址，多个邮箱用逗号分隔';}\"></td><td ><button class='ui_input_btn01' onclick='SendEmail(\"" + cid + "\",\"" + tablename + "\")'>发送</button></td></tr>";
            });

            $('#show_table2').html(items);
        }
    });
}



//返回上一级
function returnLastPage() {
    switch (flag) {
        case 0:
            break;
        case 1:
            break;
        case 2:
            search();
            break;
        case 3:{
            highchartsFlag=1;
            FindCaseByRid(temprid, temptablename);
            break;
        }
    }
}

